﻿#include "taskbusplatformfrm.h"
#include <QApplication>
#include <QDebug>
#include <QLibraryInfo>
#include <QTranslator>
#ifdef WIN32
#include <io.h>
#include <fcntl.h>
#include <windows.h>
#endif
#include <QAtomicInteger>
#include <QProcess>
#include <QSettings>
#include <QSplashScreen>
#include <QPixmap>
#include <QDir>
#include <QFileInfo>
#include <QMessageBox>
#include <QPainter>
#include "../taskbus_version.h"
#include "watchdog/tbwatchdog.h"
#include "watchdog/profile_log.h"
//全局吞吐量 global IO speed recorder
QAtomicInteger<quint64>  g_totalrev (0), g_totalsent (0);
void create_custom_item_editor();

QPixmap splash_image();

int main(int argc, char *argv[])
{
	QApplication app(argc, argv);
	//init ProfileLog
	profile_log::init();
	//If you want to do profile test, please turn this on (true)
	profile_log::set_log_state(false);
	LOG_PROFILE("Program","Main Start.");

	//Init watchdog
	tb_watch_dog().watch();

	//Change CurrentDir
	QDir dir("/");
	dir.setCurrent(app.applicationDirPath());

	QSettings settings(QCoreApplication::applicationFilePath()+".ini",QSettings::IniFormat);
	//set Plugin PATH
#ifdef Q_OS_LINUX
	QString strExePath = qgetenv("PATH");
	QString newPath = QCoreApplication::applicationDirPath();
	if (strExePath.length())
	{
		newPath += ":";
		newPath += strExePath;
	}
	qputenv("PATH",newPath.toUtf8());
#else
	QString plgPath = settings.value("settings/QT_PLUGIN_PATH",QCoreApplication::applicationDirPath()).toString();
	QString uhdPath = settings.value("settings/UHD_PKG_PATH",QCoreApplication::applicationDirPath()+"/../uhd").toString();
	QDir dir_plg (plgPath), dir_uhd(uhdPath);
	plgPath = dir_plg.absolutePath();
	uhdPath = dir_uhd.absolutePath();
	QString strUHDPath = qgetenv("UHD_PKG_PATH");
	if (!strUHDPath.length())
	{
		strUHDPath = uhdPath;
		qputenv("UHD_PKG_PATH",strUHDPath.toUtf8());
	}

	QString strPluginPath = qgetenv("QT_PLUGIN_PATH");
	QString newPlgPath = plgPath;
	if (strPluginPath.length())
	{
		newPlgPath += ";";
		newPlgPath += strPluginPath;
	}
	qputenv("QT_PLUGIN_PATH",newPlgPath.toUtf8());

	QString strExePath = qgetenv("PATH");
	QString newPath =  QCoreApplication::applicationDirPath();
	if (strExePath.length())
	{
		newPath += ";";
		newPath += strExePath;
	}
	newPath += ";" + strUHDPath+"\\bin";
	qputenv("PATH",newPath.toUtf8());
#endif

	//Install translators
	QTranslator qtTranslator;
	if (qtTranslator.load("qt_" + QLocale::system().name(),
					  QLibraryInfo::path(QLibraryInfo::TranslationsPath)))
		app.installTranslator(&qtTranslator);


	QTranslator appTranslator;
	QString strTransLocalFile =
			QCoreApplication::applicationDirPath()+"/" +
			QCoreApplication::applicationName()+"_"+
			QLocale::system().name()+".qm";
	if (appTranslator.load(strTransLocalFile ))
		app.installTranslator(&appTranslator);

	QTranslator qtTranslatorRes;
	QString strTransLocalRes =
			":/" +
			QCoreApplication::applicationName()+"_"+
			QLocale::system().name()+".qm";
	if (qtTranslatorRes.load(strTransLocalRes ))
		app.installTranslator(&qtTranslatorRes);
	//using custon item editor, for double int values.
	create_custom_item_editor();
	//show splahs screen
	QSplashScreen screen(splash_image());
	screen.show();
	app.processEvents(QEventLoop::ExcludeUserInputEvents);

	//init main frame
	taskBusPlatformFrm w;
	QObject::connect(&w,&taskBusPlatformFrm::showSplash,
					 &screen, &QSplashScreen::showMessage);
	QObject::connect(&w,&taskBusPlatformFrm::hideSplash,
					 &screen, &QSplashScreen::hide);
	app.processEvents(QEventLoop::ExcludeUserInputEvents);

#ifdef WIN32
	setmode(fileno(stdout),O_BINARY);
	setmode(fileno(stdin),O_BINARY);
#endif

	//open Cmdline
	QStringList cmdlineList = app.arguments();
	int cntv = 0;
	bool autorun = false;
	bool autohide = false;
	bool pophelp = false;
	bool next_is_title = false,next_is_modules = false;
	QString title = "";
	QStringList openFiles;
	QString modFile;
	foreach (QString argsre, cmdlineList)
	{
		if (!cntv++)
			continue;
		if (argsre=="--run"||argsre=="-r")
			autorun = true;
		else if (argsre=="--hide")
			autohide = true;
		else if (argsre=="--title"||argsre=="-t")
		{
			next_is_title = true;
		}
		else if (argsre=="--help"||argsre=="-h"||argsre=="-?")
		{
			pophelp = true;
		}
		else if (argsre=="--modules"||argsre=="-m")
		{
			next_is_modules = true;
		}
		else if (next_is_title)
		{
			title = argsre;
			next_is_title = false;
		}
		else if (next_is_modules)
		{
			next_is_modules = false;
			modFile = argsre;
		}
		else
		{
			QFileInfo info_f(argsre);
			if (info_f.exists() && info_f.isFile())
			{
				openFiles << info_f.absoluteFilePath();
			}
			else
				pophelp = true;
		}
	}

	if (pophelp)
	{
		QString argv1 = argv[0];
		QMessageBox::information(&w,"Help",
								 "Usage: \n" +
									 argv1 +
									 "\n\t --run|-r : Run Opened projects(*.tbj);"
									 "\n\t --title|-t <title>  :Set program title;"
									 "\n\t --hide :Hide mainframe;"
									 "\n\t --modules|-m <file.text> :load modules from file.text;"
									 "\n\t --help|-h|-? :Show this help message;"
								 );
		return 0;
	}
	g_totalrev = 0;
	g_totalsent = 0;

	LOG_PROFILE("Program","Main Inited.");
	if (profile_log::log_state())
		qDebug() << "Log File:"<<profile_log::url();

	//Load default modules
	QString DefaultModDefFile = QCoreApplication::applicationDirPath() + "/default_mods.text";
	QDir dirDef(QCoreApplication::applicationDirPath());
	QString mod_def = settings.value("current/mod_def",DefaultModDefFile).toString();
	//Using cmdline modfile
	QFileInfo info_moduf(modFile);
	if (modFile.length() && info_moduf.isFile())
	{
		mod_def = info_moduf.absoluteFilePath();
	}
	mod_def = dirDef.absoluteFilePath(mod_def);
	QString relp = dirDef.relativeFilePath(mod_def);
	if (relp.length()<=mod_def.length())
		mod_def = relp;
	settings.setValue("current/mod_def",mod_def);
	w.load_mod_def(mod_def);
	w.show();

	foreach (QString fm, openFiles)
	{
		w.openProject(fm,autorun);
	}
	if (title.length()>1 && title.length()<256)
		w.setWindowTitle(title);
	if (autohide)
		w.hideMainFrame();

	int ret = app.exec();
	LOG_PROFILE("Program",QString("Main End with return value %1.").arg(ret));

	return ret;
}

QPixmap splash_image()
{
	QPixmap pixmap(":/taskBus/images/taskBus.png");
	QPainter painter(&pixmap);
	QFont font = painter.font();
	font.setPointSize(14);
	painter.setFont(font);
	painter.drawText(335, 226, QString("V%1").arg(TASKBUS_VERSION));
	painter.end();
	return pixmap;
}
